from __future__ import annotations

from typing import Optional, Dict, Any
from openai import OpenAI
import os
import logging


class AIClient:
    _client: Optional[OpenAI] = None

    @classmethod
    def get_client(cls) -> OpenAI:
        if cls._client is None:
            # 仅使用通义千问 DashScope OpenAI 兼容接口
            api_key = os.getenv("DASHSCOPE_API_KEY")
            base_url = os.getenv("OPENAI_BASE_URL") or "https://dashscope.aliyuncs.com/compatible-mode/v1"
            if not api_key:
                raise RuntimeError("DASHSCOPE_API_KEY 未配置")
            kwargs: Dict[str, Any] = {}
            if base_url:
                kwargs["base_url"] = base_url
            cls._client = OpenAI(api_key=api_key, **kwargs)
        return cls._client

    @classmethod
    def chat(cls, model: str, messages: list[dict], temperature: float = 0.2, max_tokens: int | None = None, timeout: int = 1800) -> str:
        client = cls.get_client()
        # 设置请求超时
        import httpx
        timeout_obj = httpx.Timeout(timeout)
        # 兼容：若未显式传入模型，则从环境变量读取或采用默认值
        if not model:
            model = os.getenv("OPENAI_MODEL") or os.getenv("DASHSCOPE_MODEL") or "qwen-plus"
            logging.getLogger(__name__).info("AIClient using model: %s", model)
        
        resp = client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
            max_tokens=max_tokens,
            extra_body={"enable_thinking": False},
            timeout=timeout_obj,
        )
        return resp.choices[0].message.content or ""


